package ext.tianma.doc.util;

import wt.doc.WTDocument;
import wt.fc.ObjectIdentifier;
import wt.fc.ObjectReference;
import wt.fc.PersistInfo;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.iba.definition.litedefinition.AttributeDefDefaultView;
import wt.iba.definition.service.IBADefinitionHelper;
import wt.iba.value.StringValue;
import wt.query.ClassAttribute;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.query.SubSelectExpression;
import wt.vc.config.LatestConfigSpec;

public class MyDocUtil {
	
	/**
	 * 根据IBA属性获取文档对象
	 * @param ibaName
	 * @param ibaValue
	 * @return
	 * @throws Exception
	 */
	public static WTDocument getWTDocumentByIBAValue( String ibaName , String ibaValue ) throws Exception {
		WTDocument doc = null ;
		System.out.println( "Debug   getWTDocumentByIBAValue..." );
		QuerySpec qs = new QuerySpec(WTDocument.class);

		AttributeDefDefaultView addv = IBADefinitionHelper.service.getAttributeDefDefaultViewByPath(ibaName);
		
		if (addv == null){
			throw new Exception("未找到属性"+ibaName+"的定义！");
		}
		
		long ibaDefId = addv.getObjectID().getId();

		QuerySpec qsub = new QuerySpec();
		
		int index = qsub.appendClassList(StringValue.class, false);
		System.out.println( "Debug   getWTDocumentByIBAValue:"+index );
		ClassAttribute ca = new ClassAttribute(StringValue.class, 
			StringValue.IBAHOLDER_REFERENCE + "."
			+ ObjectReference.KEY + "." 
			+ ObjectIdentifier.ID);
		
		qsub.appendSelect(ca, new int[]{index}, false);
		
		qsub.appendWhere(new SearchCondition(StringValue.class, 
			StringValue.DEFINITION_REFERENCE + "."
			+ ObjectReference.KEY + "." 
			+ ObjectIdentifier.ID,
			SearchCondition.EQUAL, ibaDefId), new int[]{index});
		
		qsub.appendAnd();

		qsub.appendWhere(new SearchCondition(StringValue.class,
		StringValue.VALUE, SearchCondition.LIKE,
		ibaValue.toUpperCase()), 
		new int[]{0});

		SubSelectExpression sse = new SubSelectExpression(qsub);

		qs.appendWhere(new SearchCondition(new ClassAttribute(
			WTDocument.class, Persistable.PERSIST_INFO + "." 
			+ PersistInfo.OBJECT_IDENTIFIER + "."
			+ ObjectIdentifier.ID), SearchCondition.IN, sse), 
			new int[]{0});
			
		qs.appendAnd();
		qs.setAdvancedQueryEnabled(true);	
		qs = new LatestConfigSpec().appendSearchCriteria(qs);				
		QueryResult qr = PersistenceHelper.manager.find(qs);					
		System.out.println( "Debug    QueryResult:"+qr.size() );
		if( qr != null && qr.hasMoreElements()){
			Object obj = qr.nextElement();
			
			if(obj != null && obj instanceof WTDocument){
				doc = (WTDocument) obj ;
			}
		}
		
		return doc ;
	}
}
